﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;

using System.Threading;
using System.Diagnostics;

using System.Net;
using System.IO;
using System.Net.NetworkInformation;
using System.Management;

using System.Net.Mail;
using System.Net.Mime;

using System.Configuration;




namespace stat_agent_final
{
    public partial class Main : Form
    {
        Configuration frm2 = new Configuration();
       

        private String max;
        private String sub;
        private String temps_p;
        private String imprimante;
        private String copies;
        //private String reponse_serveur;
      

        private List<string> tab = new List<string>();


        public Main()
        {
            InitializeComponent();

        }
        private static int WM_QUERYENDSESSION = 0x11;
        private static bool systemShutdown = false;
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            if (m.Msg == WM_QUERYENDSESSION)
            {

                Email_Notify();
                web_client();
                WriteLog("cet événement se produit aprés le shutdown  / déconnexion de la session ");
                WriteLog("Heure de connexion de l'agent : " + temps_session());
                WriteLog("Durée de connection de l'opérateur : " + temps_ecoulee());
                WriteLog("Imprimente utilisée : " + imprimante_utilisee());
                WriteLog("Nopmbre de copies : " + nbre_copies());
                WriteLog("--------------------------------------------------------------------------------------------------");

                MessageBox.Show("Vous ètes entrain de fermer votre session ! ! !");

                systemShutdown = true;
            }

            // If this is WM_QUERYENDSESSION, the closing event should be
            // raised in the base WndProc.
            base.WndProc(ref m);

        } //WndProc

        private void MainFrm_Load(object sender, EventArgs e)
        {
            //Hide the main form
            base.TopMost = false;
            base.Opacity = 0.0;
            base.WindowState = FormWindowState.Minimized;
            //Register to the SessionSwitch event
            //SystemEvents.SessionEnded += new SessionEndedEventHandler(this.SystemEvents_SessionSwitch);
            //Show the tooltip for the notify icon
            this.notifyIcon1.ShowBalloonTip(0xbb8);
        }

       

        public void Email_Notify()
        {
            string mail_from = ConfigurationManager.AppSettings["mail_from"];
            string password_mail = ConfigurationManager.AppSettings["password_mail"];
            string mail_to = ConfigurationManager.AppSettings["mail_to"];

            string Body = " Heure de connexion de l'opérateur: \t " + temps_session() +
                           "\n Durée de connexion de l'opérateur:\t " + temps_ecoulee() +
                           "\n Imprimente utilisée:\t " + imprimante_utilisee() +
                           "\n Nombre de copies:\t " + nbre_copies();
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress(mail_from);
                mail.To.Add(mail_to);
               // mail.To.Add("bayrem.kaddoussi@gmail.com");

                mail.Subject = "Statistiques de l'opérateur";
                mail.Body = Body;

                SmtpServer.Port = 587;

                SmtpServer.Credentials = new System.Net.NetworkCredential(mail_from, password_mail);
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                // MessageBox.Show("Email is Sent");
            }
            catch (Exception ex)
            {
                
                WriteLog(ex.ToString()+"\n Une erreur est survenue lors de l'envoi du mail");
                MessageBox.Show("Une erreur est survenue lors de l'envoi du mail");
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void WriteLog(string Msg)
        {
            FileStream fs = new FileStream("c:\\logxxx111.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(Msg);
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

        private String temps_session()
        {
            ManagementObjectSearcher searcher =
                  new ManagementObjectSearcher("root\\CIMV2",
                  "SELECT * FROM Win32_Session ");
            foreach (ManagementObject queryObj in searcher.Get())
            {
                sub = queryObj["StartTime"].ToString();
                string sub_h = sub.Substring(8, 2);
                string sub_m = sub.Substring(10, 2);
                string sub_s = sub.Substring(12, 2);
                string sub1 = sub_h + sub_m + sub_s;

                tab.Add(sub1);
            }

            max = tab.Max();
            String max1 = max.Substring(0, 2);
            String max2 = max.Substring(2, 2);
            String max3 = max.Substring(4, 2);
            temps_p = max1 + ":" + max2 + ":" + max3;

            DateTime temps_p1 = DateTime.Parse(temps_p);

            return temps_p;


        }

        private String temps_ecoulee()
        {

            int heur = DateTime.Now.Hour;
            int min = DateTime.Now.Minute;
            int sec = DateTime.Now.Second;
            String t = String.Format("{0:00}:{1:00}:{2:00}", heur, min, sec);

            DateTime d = DateTime.Parse(t);
            DateTime temps_p1 = DateTime.Parse(temps_p);
            TimeSpan ts = d - temps_p1;


            return ts.ToString();




        }

        private String imprimante_utilisee()
        {

            ManagementObjectSearcher searcher2 =
                new ManagementObjectSearcher("root\\CIMV2",
                "Select * from Win32_PerfFormattedData_Spooler_PrintQueue  WHERE Name = 'Canon LBP2900'");

            foreach (ManagementObject queryObj in searcher2.Get())
            {

                imprimante = queryObj["Name"].ToString();

            }

            return imprimante;


        }

        private String nbre_copies()
        {

            ManagementObjectSearcher searcher2 =
                new ManagementObjectSearcher("root\\CIMV2",
                "Select * from Win32_PerfFormattedData_Spooler_PrintQueue  WHERE Name = 'Canon LBP2900'");

            foreach (ManagementObject queryObj in searcher2.Get())
            {

                copies = queryObj["TotalPagesPrinted"].ToString();

            }

            return copies;


        }

        private void web_client()
        {

            string serv_addr = ConfigurationManager.AppSettings["serv_addr"];

            try
            {
                string requestmethod = "POST";
                string postData = "id_type_doc=aaa&var_ts=" + temps_session() + "&var_te=" + temps_ecoulee() + "&var_iu=" + imprimante_utilisee() + "&var_nbc=" + nbre_copies() + "";

                //The Byte Array that will be used for writing the data to the stream.
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                string URL = "http://" + serv_addr + "/LMB/profil_collab/factures_agents/webClient_CSharp.php";
                //The type of content being send, this is almost always "application/x-www-form-urlencoded".
                string contenttype = "application/x-www-form-urlencoded";
                //What the server sends back:
                //string responseFromServer = null;
                //Here we will create the WebRequest object, and enter the URL as soon as it is created.
                WebRequest request = WebRequest.Create(URL);
                //We also need a Stream:
                Stream dataStream;
                //...And a webResponce,
                //WebResponse response;
                //don't forget the streamreader either!
                //StreamReader reader;
                //We will need to set the method used to send the data.
                request.Method = requestmethod;
                //Then the contenttype:
                request.ContentType = contenttype;
                //content length
                request.ContentLength = byteArray.Length;
                //ok, now get the request from the webRequest object, and put it into our Stream:
                dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
                //Get the responce
                //response = request.GetResponse();
                // Get the stream containing content returned by the server.
                //dataStream = response.GetResponseStream();
                //Open the responce stream:
                //reader = new StreamReader(dataStream);
                //read the content into the responcefromserver string
                //responseFromServer = reader.ReadToEnd();
                // Clean up the streams.
                //reader.Close();
                //dataStream.Close();
                //response.Close();


                //Now, display the responce!
                //Console.WriteLine(responseFromServer);
            }
            catch (WebException exp)
            {
                MessageBox.Show(exp.Message+" : Vérifiez l'url du serveur LMB", "Exception");

            }
            // textBox1.AppendText(responseFromServer);
            //return responseFromServer;

            //Done!


        }
        private void param_Click(object sender, EventArgs e)
        {
            Configuration frm = new Configuration();
            frm.Show();
            //textBox1.Text = frm2.Fo;
        }

       

      
    }
}
